<template>
  <el-form :model="form_function_choice" label-width="80px">
    <el-form-item label="GiteeToken">
      <el-input v-model="form_function_choice.access_token" placeholder="输入GiteeAPI授权码">
        <template #append>
          <el-link :underline="false" target="_blank"
                   href="https://gitee.com/profile/personal_access_tokens">
            获取授权码
          </el-link>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="代码名称">
      <el-autocomplete style="width: 100%"
                       v-model="form_function_choice.codeName"
                       :fetch-suggestions="search_code_name"
                       placeholder="输入代码名称"
                       @select="get_branched_by_code_name"
                       :disabled="form_function_choice.is_code_name_lock"
      >
        <!--        <template #prepend>https://gitee.com/src-openeuler/</template>-->
        <!--        <template #append>.git</template>-->
        <template #append v-if="!form_function_choice.is_code_name_lock">
          <el-button @click="form_function_choice.is_code_name_lock=true">
            <el-icon>
              <Unlock/>
            </el-icon>
          </el-button>
        </template>
        <template #prepend v-if="form_function_choice.is_code_name_lock">
          <el-button @click="form_function_choice.is_code_name_lock=false">
            <el-icon>
              <Lock/>
            </el-icon>
          </el-button>
        </template>
      </el-autocomplete>
    </el-form-item>
    <el-form-item label="选择分支">
      <el-cascader v-model="form_function_choice.branch_choice" :options="form_function_choice.branch_list"
                   :show-all-levels="false"/>
    </el-form-item>
    <el-form-item label="CVE编号">
      <el-button type="success" @click="get_issue_info()">获取issue</el-button>
    </el-form-item>
    <el-form-item label="Mock环境">
      <el-radio-group v-model="form_function_choice.sessionMockChoice">
        <el-radio-button v-for="(v, k) in sessionMockList" :key="k" :label="v"/>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="编译参数" v-if="form_function_choice.sessionMockChoice!==''">
      <el-radio-group v-model="form_function_choice.rpmbuild_compile_type">
        <el-radio-button label="-ba"/>
        <el-radio-button label="-bp"/>
        <el-radio-button label="-bs"/>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="上传Koji" v-if="form_function_choice.sessionMockChoice!==''">
      <el-space wrap :fill="true">
        <el-checkbox-group v-model="form_function_choice.rpmbuild_koji_choice">
          <el-checkbox label="237" border></el-checkbox>
          <el-checkbox label="238" border></el-checkbox>
          <el-checkbox label="239" border></el-checkbox>
          <el-checkbox label="242" border></el-checkbox>
        </el-checkbox-group>
      </el-space>
    </el-form-item>
    <el-form-item v-if="is_in_list('237', form_function_choice.rpmbuild_koji_choice)" label="237Tag">
      <el-input v-model="form_function_choice.tag_237"/>
    </el-form-item>
    <el-form-item v-if="is_in_list('238', form_function_choice.rpmbuild_koji_choice)" label="238Tag">
      <el-input v-model="form_function_choice.tag_238"/>
    </el-form-item>
    <el-form-item v-if="is_in_list('239', form_function_choice.rpmbuild_koji_choice)" label="239Tag">
      <el-input v-model="form_function_choice.tag_239"/>
    </el-form-item>
    <el-form-item v-if="is_in_list('242', form_function_choice.rpmbuild_koji_choice)" label="242Tag">
      <el-input v-model="form_function_choice.tag_242"/>
    </el-form-item>
  </el-form>
  <el-button type="success" v-if="!form_function_choice.is_session_init" @click="session_init">初始化会话</el-button>
  <el-collapse v-if="form_function_choice.is_session_init" v-model="form_function_choice.func_btn_activate_name">
    <el-collapse-item title="设置管理" name="1">
      <el-space wrap spacer="|">
        <!-- <el-button type="success" @click="session_setting_write">同步设置</el-button>-->
        <el-button type="danger" @click="session_setting_read">加载设置</el-button>
        <el-radio-group v-model="form_function_choice.is_setting_auto_sync">
          <el-radio-button label="开启同步"/>
          <el-radio-button label="关闭同步"/>
        </el-radio-group>
      </el-space>
    </el-collapse-item>
    <el-collapse-item title="Git操作" name="2">
      <el-space wrap spacer="|">
        <el-button type="success" @click="git_src_from_gitee">拉取整个项目</el-button>
        <el-button type="success" @click="git_spec_from_gitee">仅拉取SPEC文件</el-button>
      </el-space>
    </el-collapse-item>
    <el-collapse-item title="初始化管理" name="3">
      <el-space wrap spacer="|">
        <el-button type="success" @click="refresh_gitee_token">初始化Mock</el-button>
        <el-button type="success">创建Rpmbuild目录</el-button>
      </el-space>
    </el-collapse-item>
    <el-collapse-item title="行为管理" name="4">
      <el-space wrap spacer="|">
        <el-button type="success">开始编译</el-button>
        <el-button type="success">提交Koji</el-button>
      </el-space>
    </el-collapse-item>
  </el-collapse>
</template>

<script>
import axios from 'axios'
import {ElNotification} from 'element-plus'
import {Unlock, Lock} from '@element-plus/icons-vue'

export default {
  name: "windowFunctionChoice",
  props: {
    sessionToken: String
  },
  components: {
    Unlock,
    Lock,
  },
  data() {
    return {

      sessionMockList: ["sp1", "sp2", "sp2_shao"],
      form_function_choice: {
        is_session_init: false,
        is_code_name_lock: false,
        is_setting_auto_sync: "关闭同步",
        access_token: 'a54d86fde6a5be2d92c542264e25210f',
        username: "",
        changelog_title: "",
        branch_list: [],
        branch_choice: ["openEuler-20.03-LTS-SP1"],
        codeName: '',
        cve_number: "",
        sessionMockChoice: '',
        file_download_link: '',
        rpmbuild_compile_type: '',
        rpmbuild_koji_choice: [],
        tag_237: "v10-sp1.1-updates",
        tag_238: "v10-sp2-updates",
        tag_239: "v10-sp2-updates-5000xxx",
        tag_242: "ns8.6",
        func_btn_activate_name: "1",
      }
    }
  },
  methods: {
    //获取分支：https://gitee.com/api/v5/repos/src-openeuler/rpm/branches
    refresh_gitee_token() {
      // https://gitee.com/oauth/authorize?client_id=8ac7a94ff19ddb4b9d267d525c048e2845f589cf3b1e8d09ef2568ca63f74603&response_type=code
      // https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}
      // let url = "https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token=" + this.form_function_choice.access_token
      let url = "https://gitee.com/oauth/authorize?client_id=8ac7a94ff19ddb4b9d267d525c048e2845f589cf3b1e8d09ef2568ca63f74603&response_type=code"
      axios.get(url).then(function (response) {
        console.log(response)
      }).catch(function (error) { // 请求失败处理
        console.log(error);
        ElNotification({title: "GiteeAPI请求失败，重新获取授权码", type: 'error',})
      });
    },
    search_code_name(keyword, cb) {
      if (keyword === "") return
      let url = "https://gitee.com/api/v5/search/repositories?access_token=" + this.form_function_choice.access_token +
          "&q=" + keyword +
          "&page=1&per_page=100&owner=src-openeuler&order=desc"
      axios.get(url).then(function (response) {
        let cand_code_name = []
        for (let i = 0; i < response.data.length; i++) {
          cand_code_name.push({value: response.data[i].name})
        }
        cb(cand_code_name)
      }).catch(function (error) { // 请求失败处理
        console.log(error);
        ElNotification({title: "GiteeAPI请求失败，重新获取授权码", type: 'error',})
      });
    },
    get_branched_by_code_name() {
      let obj_this = this
      if (this.form_function_choice.codeName === "")
        return
      let url = "https://gitee.com/api/v5/repos/src-openeuler/" +
          this.form_function_choice.codeName + "/branches?access_token=" + this.form_function_choice.access_token
      axios.get(url).then(function (response) {
        obj_this.form_function_choice.branch_list = []
        for (let i = 0; i < response.data.length; i++) {
          obj_this.form_function_choice.branch_list.push({value: response.data[i].name, label: response.data[i].name})
        }
      }).catch(function (error) { // 请求失败处理
        console.log(error);
        ElNotification({title: "GiteeAPI请求失败，重新获取授权码", type: 'error',})
      });
    },
    is_in_list(v, list) {
      return list.includes(v)
    },
    file_upload() {
      console.log("上传文件")
    },
    get_issue_info() {
      if (this.form_function_choice.codeName === "") {
        ElNotification({title: "代码名称不能为空", type: 'error',})
        return
      }
      if (this.form_function_choice.access_token === "") {
        ElNotification({title: "Gitee 授权码不能为空", type: 'error',})
        return
      }
      this.$store.state.obj_windowEditorManage.addTab_gitee_issue_page_out(this.form_function_choice.codeName, this.form_function_choice.access_token)
    },
    session_init() {
      let obj_this = this
      let data = {
        "session_token": obj_this.sessionToken,
        "session_function": "session_init"
      }
      axios.post('/session_function_do', data).then(function (response) {
        obj_this.form_function_choice.is_session_init = true
        // obj_this.session_setting_write()
        console.log(response)
      }).catch(function (error) { // 请求失败处理
        console.log(error);
      });
    },
    session_setting_write() {
      let obj_this = this
      let data = {
        "session_token": obj_this.sessionToken,
        "session_function": "session_setting_write",
        "session_setting": obj_this.form_function_choice
      }
      axios.post('/session_function_do', data).then(function (response) {
        ElNotification({
          title: response.data.msg_str,
          type: 'success',
        })
      }).catch(function (error) { // 请求失败处理
        console.log(error);
      });
    },
    session_setting_read() {
      let obj_this = this
      let data = {
        "session_token": obj_this.sessionToken,
        "session_function": "session_setting_read"
      }
      axios.post('/session_function_do', data).then(function (response) {
        ElNotification({
          title: response.data.msg_str,
          type: 'success',
        })
        Object.assign(obj_this.form_function_choice, response.data.data)
      }).catch(function (error) { // 请求失败处理
        console.log(error);
      });
    },
    git_src_from_gitee() {
      let obj_this = this
      if (obj_this.form_function_choice.codeName === "") {
        ElNotification({
          title: "代码名称不能为空",
          type: 'error',
        })
        return
      }
      if (obj_this.form_function_choice.branch_choice[0] === "") {
        ElNotification({
          title: "代码分支不能为空",
          type: 'error',
        })
        return
      }
      ElNotification({
        title: '开始拉取源码',
        type: 'success',
      })
      obj_this.form_function_choice.is_code_name_lock = true
      let data = {
        "session_token": obj_this.sessionToken,
        "session_function": "git_src_from_gitee",
        "code_name": obj_this.form_function_choice.codeName,
        "code_branch": obj_this.form_function_choice.branch_choice[0]
      }
      axios.post('/session_function_do', data).then(function (response) {
        obj_this.$store.state.obj_windowTaskManage.is_show_window_task = true // 打开任务窗口
        ElNotification({
          title: response.data.msg_str,
          type: 'success',
        })
        // obj_this.session_setting_write()
      }).catch(function (error) { // 请求失败处理
        console.log(error);
      });
      // this.isSessionCreated = true;
    },
    check_para_gitee() {
      if (this.form_function_choice.codeName === "") {
        ElNotification({
          title: "代码名称不能为空",
          type: 'error',
        })
        return false
      }
      if (this.form_function_choice.branch_choice[0] === "") {
        ElNotification({
          title: "代码分支不能为空",
          type: 'error',
        })
        return false
      }
      return true
    },
    down_spec_file(spec_blob_url, file_name) {
      // "session_token": session_token,
      //       "download_url": request.json.get('download_url', ''),
      //       "download_name"
      let obj_this = this
      let data = {
        "session_token": obj_this.sessionToken,
        "session_function": "git_spec_from_gitee",
        "download_url": spec_blob_url,
        "download_name": obj_this.form_function_choice.branch_choice[0] + "_" +
            obj_this.form_function_choice.codeName + "_" + file_name,
      }
      axios.post('/session_function_do', data).then(function (response) {
        ElNotification({
          title: response.data.msg_str,
          type: 'success',
        })
        // obj_this.session_setting_write()
      }).catch(function (error) { // 请求失败处理
        console.log(error);
      });
    },
    git_spec_from_gitee() {
      // 获取所有文件：https://gitee.com/api/v5/repos/src-openeuler/libwd/git/trees/openEuler-20.03-LTS-SP1
      let obj_this = this
      if (!obj_this.check_para_gitee()) return
      obj_this.form_function_choice.is_code_name_lock = true
      let url = "https://gitee.com/api/v5/repos/src-openeuler/" +
          this.form_function_choice.codeName + "/git/trees/" + this.form_function_choice.branch_choice +
          "?access_token=" + this.form_function_choice.access_token
      axios.get(url).then(function (response) {
        let file_list = response.data.tree
        for (let i = 0; i < file_list.length; i++) {
          if (file_list[i].path.endsWith(".spec")) {
            obj_this.down_spec_file(file_list[i].url, file_list[i].path)
          }
        }
      }).catch(function (error) { // 请求失败处理
        console.log(error);
        ElNotification({title: "GiteeAPI请求失败，重新获取授权码", type: 'error',})
      });
    },
  },
  created() {
    this.session_setting_read()
  },
  watch: {}
}
</script>

<style scoped>
</style>